import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Input, Modal, Spin, Select, message, notification } from 'antd';

const FormItem = Form.Item;
const { Option } = Select;

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 19 },
  },
};

@connect(({ productOrder, logisticsCompany, loading }) => ({
  productOrder,
  logisticsCompany,
  loading: loading.models.productOrder,
}))
@Form.create()
class SendOutModal extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      logisticsList: [],
      logisticsLoading: false,
      logisticsSelectName: '',
      logisticsSelectCode: '',
      metaData: null,
      saving: false,
      visible: false,
    };
  }

  componentDidMount() {
    const { visible, data } = this.props;
    this.setState({ visible });
    this.setState({ metaData: data });

    this.loadData();
  }

  componentWillReceiveProps(nextProps) {
    const { visible: visiblePre } = this.state;
    const { form, visible, data } = nextProps;
    this.setState({ metaData: data });
    this.setState({ visible });

    if (visiblePre === false && visible === true) {
      form.resetFields();
    }
  }

  onLogisticSelect = (value, option) => {
    const { name, code } = option.props;

    this.setState({
      logisticsSelectName: name,
      logisticsSelectCode: code,
    });
  };

  loadData = () => {
    const { dispatch } = this.props;

    this.setState({ logisticsLoading: true });

    dispatch({
      type: 'logisticsCompany/list',
    }).then(() => {
      this.setState({ logisticsLoading: false });

      const {
        logisticsCompany: { data },
      } = this.props;

      const { status } = data;

      if (status === 200) {
        const { list: listData } = data;
        this.setState({ logisticsList: listData });
      }
    });
  };

  handleOk = e => {
    e.preventDefault();
    const { dispatch, form, afterOK } = this.props;
    const { metaData, logisticsSelectName, logisticsSelectCode } = this.state;

    form.validateFields((err, values) => {
      if (!err) {
        if ((`${values.logisticsKey}` || '') === '') {
          message.error('请选择物流方式！');
          return;
        }

        if ((logisticsSelectName || '') === '') {
          message.error('请选择物流方式！');
          return;
        }

        if ((logisticsSelectCode || '') === '') {
          message.error('请选择物流方式！');
          return;
        }

        const submitValue = values;
        delete submitValue.logisticsKey;
        submitValue.productOrderId = metaData.productOrderId;
        submitValue.logisticsCom = logisticsSelectName;
        submitValue.logisticsComCode = logisticsSelectCode;

        this.setState({ saving: true });

        dispatch({
          type: 'productOrder/sendOut',
          payload: submitValue,
        }).then(() => {
          this.setState({ saving: false });

          const {
            productOrder: { data },
          } = this.props;

          const { status } = data;

          if (status === 200) {
            this.setState({ visible: false });
            const { orderNo } = metaData;

            afterOK(data, () => {
              notification.success({
                placement: 'bottomRight',
                message: '操作结果',
                description: `订单号${orderNo}的订单已设定为已发货。`,
              });
            });
          }
        });
      }
    });
  };

  handleCancel = e => {
    e.preventDefault();
    const { afterCancel } = this.props;
    // this.setState({ visible: false });
    afterCancel();
  };

  render() {
    const { form } = this.props;
    const { visible, metaData, logisticsList, saving, logisticsLoading } = this.state;
    const { getFieldDecorator } = form;

    return (
      <Modal
        title="发货物流信息"
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
      >
        <Spin spinning={saving || logisticsLoading}>
          <Form>
            <FormItem {...formItemLayout} label="订单描述">
              {(metaData || { description: '' }).description}
            </FormItem>
            <FormItem {...formItemLayout} label="物流方式" help="请在此选择物流方式。">
              {getFieldDecorator('logisticsKey', {
                rules: [{ required: true, message: '请选择物流方式!' }],
              })(
                <Select
                  style={{ width: '100%' }}
                  showSearch
                  placeholder="请选择物流方式"
                  onSelect={(value, option) => {
                    this.onLogisticSelect(value, option);
                  }}
                >
                  {logisticsList.map(d => (
                    <Option key={d.key} name={d.name} code={d.code}>
                      {d.name}
                    </Option>
                  ))}
                </Select>
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="物流单号"
              hasFeedback
              help="请在此输入您的物流单号。"
            >
              {getFieldDecorator('logisticsNu', {
                rules: [{ required: true, message: '请输入物流单号!' }],
              })(<Input placeholder="请输入物流单号" />)}
            </FormItem>
          </Form>
        </Spin>
      </Modal>
    );
  }
}

export default SendOutModal;
